package Demo;

import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2022-11-27
 * Time: 15:04
 */
public class Thread_Demo3 {

    private static long sum1;
    private static long sum2;

    /**
     *  多线程计算一千万个随机数的奇偶之和
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {

        int[] arr = new int[1000_0000];
        Random random = new Random();

        for (int i = 0; i < arr.length; i++) {
            arr[i] = random.nextInt(100) + 1;
        }

        Thread t1 = new Thread(() -> {

            for (int j = 0; j < arr.length; j += 2) {
                sum1 += arr[j];
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 1; i < arr.length; i += 2) {
                sum2 += arr[i];
            }
        });

        // 计算开始时间
        long start = System.currentTimeMillis();

        t1.start();
        t2.start();
        // 阻塞等待 main 线程
        t1.join();
        t2.join();

        System.out.println("总和为:" + sum1 + sum2);
        long end = System.currentTimeMillis();
        System.out.println("共计时:" + (end - start) + "ms");
    }
}
